package pnu.ssm.sbmother;

import java.util.*;

import pnu.ssm.adapter.*;
import pnu.ssm.appinfo.*;
import pnu.ssm.http.*;
import pnu.ssm.key.*;
import android.annotation.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;

@SuppressLint("ValidFragment")
public class AndroidAppTab extends Fragment implements Button.OnClickListener, OnQueryTextListener, OnCloseListener {

	private static final String TAG = "AndroidAppTab";
	private static final int NOTIFY_ADAPTER = 0;

	ArrayList<AppInfo> appInfoList;
	ListView listViewAppInfo;
	AppInfoListAdapter appInfoListAdapter;

	Button btnUpdateAppList;
	Button btnProhibitionAppList;

	ProgressDialog progressDialog;

	HttpConnectorParent httpConnector;
	SharedPreferences pref;
	LayoutInflater inflater;
	String child_num;

	Handler androidAppTabHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NOTIFY_ADAPTER:
				appInfoListAdapter.notifyDataSetChanged();
				break;
			default:
				Log.e(TAG, "handler error " + msg.what);
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		setHasOptionsMenu(true);
		View view = inflater.inflate(R.layout.tab_android, null);
		listViewAppInfo = (ListView) view.findViewById(R.id.lv_androidAppList);
		appInfoList = new ArrayList<AppInfo>();

		appInfoListAdapter = new AppInfoListAdapter(getActivity(),
				R.layout.row_tab_android_app_list, appInfoList);
		listViewAppInfo.setAdapter(appInfoListAdapter);

		btnUpdateAppList = (Button) view.findViewById(R.id.btn_updateAndroidAppList);
		btnProhibitionAppList = (Button) view.findViewById(R.id.btn_prohibitionAndroidAppList);

		btnUpdateAppList.setOnClickListener(this);
		btnProhibitionAppList.setOnClickListener(this);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.httpConnector = HttpConnectorParent.getInstance();
		this.pref = getActivity().getSharedPreferences(Key.prefKey,
				Context.MODE_PRIVATE);
		this.progressDialog = new ProgressDialog(getActivity());
		this.progressDialog.setMessage("Wait...");
		this.progressDialog.setCancelable(true);
		this.progressDialog.setIndeterminate(true);
		this.child_num = Key.SELECTED_CHILD_NUM;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_main, menu);

		SearchView view = (SearchView)menu.findItem(R.id.menu_main_search).getActionView();
		ActionBar actionBar = getActivity().getActionBar();
		actionBar.setTitle("잠금");
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);

		view.setOnQueryTextListener(this);
		view.setOnCloseListener(this);
		view.setQueryHint("앱 이름 검색");
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.menu_main_setting :
			Intent activity = new Intent(getActivity(), SettingActivity.class);
			startActivity(activity);
			break;
		case android.R.id.home :
			getActivity().finish();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_updateAndroidAppList) {
			new AppListAsyncTask().execute(null, null, null);
		} else if (id == R.id.btn_prohibitionAndroidAppList) {
			new ForbiddenAppListAsyncTask().execute(null, null, null);
		};
	}

	class AppListAsyncTask extends AsyncTask<Void, Void, Void>{
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.show();
		};

		@Override
		protected Void doInBackground(Void... params) {
			String parent_num = pref.getString(Key.parent_num, "");
			if (parent_num != null) {
				List<AppInfo> list = httpConnector
						.getChildAppList(child_num);
				appInfoList.clear();
				for (AppInfo info : list) {
					appInfoList.add(info);
				}
				androidAppTabHandler.sendEmptyMessage(NOTIFY_ADAPTER);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
		}
	}

	class ForbiddenAppListAsyncTask extends AsyncTask<Void, Void, Void>{
		protected void onPreExecute() {
			progressDialog.show();
		};

		@Override
		protected Void doInBackground(Void... params) {
			ArrayList<AppInfo> appInfoTempList = new ArrayList<AppInfo>();
			for (AppInfo info : appInfoList) {
				if (info.isChanged()) {
					appInfoTempList.add(info);
					info.setChanged(false);
				}
			}
			String parent_num = pref.getString(Key.parent_num,"nothing");
			if (!parent_num.equals("nothing"))
				httpConnector.sendForbiddenAppList(appInfoTempList,child_num);
			return null;
		}

		protected void onPostExecute(Void result) {
			progressDialog.dismiss();
		};
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		ArrayList<AppInfo> temp = new ArrayList<AppInfo>();

		for(AppInfo a : appInfoList) {
			AppInfo t = new AppInfo(arg0, arg0);
			if(a.equals(t)) {
				temp.add(a);
			}
		}

		appInfoListAdapter.setList(temp);
		appInfoListAdapter.notifyDataSetChanged();

		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		ArrayList<AppInfo> temp = new ArrayList<AppInfo>();

		for(AppInfo a : appInfoList) {
			AppInfo t = new AppInfo(arg0, arg0);
			if(a.equals(t)) {
				temp.add(a);
			}
		}

		appInfoListAdapter.setList(temp);
		appInfoListAdapter.notifyDataSetChanged();

		return false;
	}

	@Override
	public boolean onClose() {
		appInfoListAdapter.setList(appInfoList);
		appInfoListAdapter.notifyDataSetChanged();

		return false;
	}
}
